package org.jeecg.modules.door.controller;

import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.basic.demo.apartment.mapper.LwgyBaseApartmentMapper;
import org.jeecg.modules.door.entity.GroupRoomVo;
import org.jeecg.modules.door.entity.GroupUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import java.util.Arrays;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.door.entity.LwgyEglockGrouprightuser;
import org.jeecg.modules.door.entity.LwgyEglockGrouprightlock;
import org.jeecg.modules.door.entity.LwgyEglockGroupright;
import org.jeecg.modules.door.service.ILwgyEglockGrouprightService;
import org.jeecg.modules.door.service.ILwgyEglockGrouprightuserService;
import org.jeecg.modules.door.service.ILwgyEglockGrouprightlockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 门锁分组管理
 * @Author: jeecg-boot
 * @Date:   2022-06-15
 * @Version: V1.0
 */
@Api(tags="门锁分组管理")
@RestController
@RequestMapping("/door/lwgyEglockGroupright")
@Slf4j
public class LwgyEglockGrouprightController extends JeecgController<LwgyEglockGroupright, ILwgyEglockGrouprightService> {

	@Autowired
	private ILwgyEglockGrouprightService lwgyEglockGrouprightService;

	@Autowired
	private ILwgyEglockGrouprightuserService lwgyEglockGrouprightuserService;

	@Autowired
	private ILwgyEglockGrouprightlockService lwgyEglockGrouprightlockService;

	@Autowired
	 private LwgyBaseApartmentMapper LwgyBaseApartmentMapper;



	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param lwgyEglockGroupright
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "门锁分组管理-分页列表查询")
	@ApiOperation(value="门锁分组管理-分页列表查询", notes="门锁分组管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(LwgyEglockGroupright lwgyEglockGroupright,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<LwgyEglockGroupright> queryWrapper = QueryGenerator.initQueryWrapper(lwgyEglockGroupright, req.getParameterMap());
		Page<LwgyEglockGroupright> page = new Page<LwgyEglockGroupright>(pageNo, pageSize);
		IPage<LwgyEglockGroupright> pageList = lwgyEglockGrouprightService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param lwgyEglockGroupright
     * @return
     */
    @AutoLog(value = "门锁分组管理-添加")
    @ApiOperation(value="门锁分组管理-添加", notes="门锁分组管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody LwgyEglockGroupright lwgyEglockGroupright) {
        lwgyEglockGrouprightService.save(lwgyEglockGroupright);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param lwgyEglockGroupright
     * @return
     */
    @AutoLog(value = "门锁分组管理-编辑")
    @ApiOperation(value="门锁分组管理-编辑", notes="门锁分组管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody LwgyEglockGroupright lwgyEglockGroupright) {
        lwgyEglockGrouprightService.updateById(lwgyEglockGroupright);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "门锁分组管理-通过id删除")
    @ApiOperation(value="门锁分组管理-通过id删除", notes="门锁分组管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        lwgyEglockGrouprightService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "门锁分组管理-批量删除")
    @ApiOperation(value="门锁分组管理-批量删除", notes="门锁分组管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.lwgyEglockGrouprightService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyEglockGroupright lwgyEglockGroupright) {
        return super.exportXls(request, lwgyEglockGroupright, LwgyEglockGroupright.class, "门锁分组管理");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LwgyEglockGroupright.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-分组人员管理-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "分组人员管理-通过主表ID查询")
	@ApiOperation(value="分组人员管理-通过主表ID查询", notes="分组人员管理-通过主表ID查询")
	@GetMapping(value = "/listLwgyEglockGrouprightuserByMainId")
    public Result<?> listLwgyEglockGrouprightuserByMainId(LwgyEglockGrouprightuser lwgyEglockGrouprightuser,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<LwgyEglockGrouprightuser> queryWrapper = QueryGenerator.initQueryWrapper(lwgyEglockGrouprightuser, req.getParameterMap());
        Page<LwgyEglockGrouprightuser> page = new Page<LwgyEglockGrouprightuser>(pageNo, pageSize);
        IPage<LwgyEglockGrouprightuser> pageList = lwgyEglockGrouprightuserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param lwgyEglockGrouprightuser
	 * @return
	 */
	@AutoLog(value = "分组人员管理-添加")
	@ApiOperation(value="分组人员管理-添加", notes="分组人员管理-添加")
	@PostMapping(value = "/addLwgyEglockGrouprightuser")
	public Result<?> addLwgyEglockGrouprightuser(@RequestBody LwgyEglockGrouprightuser lwgyEglockGrouprightuser) {
		lwgyEglockGrouprightuserService.save(lwgyEglockGrouprightuser);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param lwgyEglockGrouprightuser
	 * @return
	 */
	@AutoLog(value = "分组人员管理-编辑")
	@ApiOperation(value="分组人员管理-编辑", notes="分组人员管理-编辑")
	@PutMapping(value = "/editLwgyEglockGrouprightuser")
	public Result<?> editLwgyEglockGrouprightuser(@RequestBody LwgyEglockGrouprightuser lwgyEglockGrouprightuser) {
		lwgyEglockGrouprightuserService.updateById(lwgyEglockGrouprightuser);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "分组人员管理-通过id删除")
	@ApiOperation(value="分组人员管理-通过id删除", notes="分组人员管理-通过id删除")
	@DeleteMapping(value = "/deleteLwgyEglockGrouprightuser")
	public Result<?> deleteLwgyEglockGrouprightuser(@RequestParam(name="id",required=true) String id) {
		lwgyEglockGrouprightuserService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "分组人员管理-批量删除")
	@ApiOperation(value="分组人员管理-批量删除", notes="分组人员管理-批量删除")
	@DeleteMapping(value = "/deleteBatchLwgyEglockGrouprightuser")
	public Result<?> deleteBatchLwgyEglockGrouprightuser(@RequestParam(name="ids",required=true) String ids) {
	    this.lwgyEglockGrouprightuserService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportLwgyEglockGrouprightuser")
    public ModelAndView exportLwgyEglockGrouprightuser(HttpServletRequest request, LwgyEglockGrouprightuser lwgyEglockGrouprightuser) {
		 // Step.1 组装查询条件
		 QueryWrapper<LwgyEglockGrouprightuser> queryWrapper = QueryGenerator.initQueryWrapper(lwgyEglockGrouprightuser, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<LwgyEglockGrouprightuser> pageList = lwgyEglockGrouprightuserService.list(queryWrapper);
		 List<LwgyEglockGrouprightuser> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "分组人员管理"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, LwgyEglockGrouprightuser.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("分组人员管理报表", "导出人:" + sysUser.getRealname(), "分组人员管理"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importLwgyEglockGrouprightuser/{mainId}")
    public Result<?> importLwgyEglockGrouprightuser(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<LwgyEglockGrouprightuser> list = ExcelImportUtil.importExcel(file.getInputStream(), LwgyEglockGrouprightuser.class, params);
				 for (LwgyEglockGrouprightuser temp : list) {
                    temp.setGroupId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 lwgyEglockGrouprightuserService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-分组人员管理-end----------------------------------------------*/

    /*--------------------------------子表处理-分组房间管理-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "分组房间管理-通过主表ID查询")
	@ApiOperation(value="分组房间管理-通过主表ID查询", notes="分组房间管理-通过主表ID查询")
	@GetMapping(value = "/listLwgyEglockGrouprightlockByMainId")
    public Result<?> listLwgyEglockGrouprightlockByMainId(LwgyEglockGrouprightlock lwgyEglockGrouprightlock,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<LwgyEglockGrouprightlock> queryWrapper = QueryGenerator.initQueryWrapper(lwgyEglockGrouprightlock, req.getParameterMap());
        Page<LwgyEglockGrouprightlock> page = new Page<LwgyEglockGrouprightlock>(pageNo, pageSize);
        IPage<LwgyEglockGrouprightlock> pageList = lwgyEglockGrouprightlockService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param lwgyEglockGrouprightlock
	 * @return
	 */
	@AutoLog(value = "分组房间管理-添加")
	@ApiOperation(value="分组房间管理-添加", notes="分组房间管理-添加")
	@PostMapping(value = "/addLwgyEglockGrouprightlock")
	public Result<?> addLwgyEglockGrouprightlock(@RequestBody LwgyEglockGrouprightlock lwgyEglockGrouprightlock) {
		lwgyEglockGrouprightlockService.save(lwgyEglockGrouprightlock);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param lwgyEglockGrouprightlock
	 * @return
	 */
	@AutoLog(value = "分组房间管理-编辑")
	@ApiOperation(value="分组房间管理-编辑", notes="分组房间管理-编辑")
	@PutMapping(value = "/editLwgyEglockGrouprightlock")
	public Result<?> editLwgyEglockGrouprightlock(@RequestBody LwgyEglockGrouprightlock lwgyEglockGrouprightlock) {
		lwgyEglockGrouprightlockService.updateById(lwgyEglockGrouprightlock);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "分组房间管理-通过id删除")
	@ApiOperation(value="分组房间管理-通过id删除", notes="分组房间管理-通过id删除")
	@DeleteMapping(value = "/deleteLwgyEglockGrouprightlock")
	public Result<?> deleteLwgyEglockGrouprightlock(@RequestParam(name="id",required=true) String id) {
		lwgyEglockGrouprightlockService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "分组房间管理-批量删除")
	@ApiOperation(value="分组房间管理-批量删除", notes="分组房间管理-批量删除")
	@DeleteMapping(value = "/deleteBatchLwgyEglockGrouprightlock")
	public Result<?> deleteBatchLwgyEglockGrouprightlock(@RequestParam(name="ids",required=true) String ids) {
	    this.lwgyEglockGrouprightlockService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportLwgyEglockGrouprightlock")
    public ModelAndView exportLwgyEglockGrouprightlock(HttpServletRequest request, LwgyEglockGrouprightlock lwgyEglockGrouprightlock) {
		 // Step.1 组装查询条件
		 QueryWrapper<LwgyEglockGrouprightlock> queryWrapper = QueryGenerator.initQueryWrapper(lwgyEglockGrouprightlock, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<LwgyEglockGrouprightlock> pageList = lwgyEglockGrouprightlockService.list(queryWrapper);
		 List<LwgyEglockGrouprightlock> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "分组房间管理"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, LwgyEglockGrouprightlock.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("分组房间管理报表", "导出人:" + sysUser.getRealname(), "分组房间管理"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importLwgyEglockGrouprightlock/{mainId}")
    public Result<?> importLwgyEglockGrouprightlock(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<LwgyEglockGrouprightlock> list = ExcelImportUtil.importExcel(file.getInputStream(), LwgyEglockGrouprightlock.class, params);
				 for (LwgyEglockGrouprightlock temp : list) {
                    temp.setGroupId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 lwgyEglockGrouprightlockService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-分组房间管理-end----------------------------------------------*/


	 @RequestMapping(value = "/addGroupUser", method = RequestMethod.POST)
	 public Result<String> addGroupUser(@RequestBody GroupUserVo groupUserVO) {
		 Result<String> result = new Result<String>();
		 try {
			 String groupId = groupUserVO.getGroupId();
			 for (String sysUserId : groupUserVO.getUserIdList()) {

				 LwgyEglockGrouprightuser lwgyEglockGrouprightuser = new LwgyEglockGrouprightuser();
				 lwgyEglockGrouprightuser.setGroupId(groupId);
				 lwgyEglockGrouprightuser.setPersonId(sysUserId);
				 lwgyEglockGrouprightuserService.saveOrUpdate(lwgyEglockGrouprightuser);
			 }
			 result.setMessage("添加成功!");
			 result.setSuccess(true);
			 return result;
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 result.setSuccess(false);
			 result.setMessage("出错了: " + e.getMessage());
			 return result;
		 }
	 }



	 @RequestMapping(value = "/addGroupRoom", method = RequestMethod.POST)
	 public Result<String> addGroupRoom(@RequestBody GroupRoomVo groupRoomVO) {
		 Result<String> result = new Result<String>();
		 try {
		 	String xq,lh,ch,fjh;
			 String groupId = groupRoomVO.getGroupId();
			 for (String sysRoomId : groupRoomVO.getRoomIdList()) {
				 LwgyEglockGrouprightlock lwgyEglockGrouprightlock = new LwgyEglockGrouprightlock();
				 //通过id获取房间信息
				 List<Map<String,String>> list =  LwgyBaseApartmentMapper.getFjInfoById(sysRoomId);
				 if(list.size()>0){
					 Map map= list.get(0);
					 lwgyEglockGrouprightlock.setXq(map.get("xq").toString());
					 lwgyEglockGrouprightlock.setLh(map.get("lh").toString());
					 lwgyEglockGrouprightlock.setUnit(map.get("unit").toString());
					 lwgyEglockGrouprightlock.setCh(map.get("ch").toString());
					 lwgyEglockGrouprightlock.setFjh(map.get("fjh").toString());
				 }
				 lwgyEglockGrouprightlock.setGroupId(groupId);
				 lwgyEglockGrouprightlock.setRoomId(sysRoomId);
				 lwgyEglockGrouprightlockService.saveOrUpdate(lwgyEglockGrouprightlock);
			 }
			 result.setMessage("添加成功!");
			 result.setSuccess(true);
			 return result;
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 result.setSuccess(false);
			 result.setMessage("出错了: " + e.getMessage());
			 return result;
		 }
	 }

}
